package com.yds.developtools.utils

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.*
import android.net.ConnectivityManager
import android.net.Network
import android.net.NetworkRequest
import android.os.Build
import android.provider.Settings
import androidx.annotation.RequiresApi

/**
 * 作者:     YDS
 * 创建时间: 2023/5/29 15:27
 * 页面描述: 网络状态-帮助类
 */
@Suppress("unused")
object YDSNetworkHelper {

    private var connManager: ConnectivityManager? = null

    /**
     * 判断网络是否可用（所有网络类型）
     *
     * @param context
     * @return
     */
    fun isNetworkAvailable(context: Context?): Boolean {
        if (context != null) {
            connManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val networkInfo = connManager!!.activeNetworkInfo
            if (networkInfo != null) {
                return networkInfo.isAvailable
            }
        }
        return false
    }

    /**
     * 判断网络是否可用（一直监听网络状态）
     * @param isAlert 是否弹窗
     * @param onNetConnectListener 网络状态监听
     */
    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    @SuppressLint("MissingPermission")
    fun Context.initNetworkAvailable(
        isAlert: Boolean = false,
        onNetConnectListener: OnNetConnectListener
    ) {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        connectivityManager.registerNetworkCallback(
            NetworkRequest.Builder().build(),
            object : ConnectivityManager.NetworkCallback() {
                override fun onAvailable(network: Network) {
                    // 网络连接可用
                    onNetConnectListener.onNetAvailable(network)
                }

                override fun onLost(network: Network) {
                    // 网络连接断开
                    onNetConnectListener.onNetLost(network)
                    // 是否提示网络断开
                    if (isAlert) networkAlert()
                }
            })
    }

    /*** 作者: YDS 时间: 2023/5/29 15:26 描述: 网络监听 ***/
    interface OnNetConnectListener {
        fun onNetAvailable(network: Network)
        fun onNetLost(network: Network)
    }

    /*** 作者: YDS 时间: 2023/5/29 15:52 描述: 网络断开连接提示 ***/
    private fun Context.networkAlert() {
        val builder = AlertDialog.Builder(this)
        builder.setTitle("提示：网络异常").setMessage("是否对网络进行设置?")
        builder.setPositiveButton("是") { dialog, _ ->
            Intent(Settings.ACTION_WIFI_SETTINGS).apply {
                startActivity(this)
            }
            dialog.dismiss()
        }
        builder.setNegativeButton("否") { dialog, _ -> dialog.cancel() }
        builder.show()
    }
}